package com.zhuhao.design_mode.behavioral_pattern.interator.full_demo;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Iterator;
import java.util.NoSuchElementException;

// 实体类
@Getter
@AllArgsConstructor
class Book {
    private final String name;
}

// 集合接口（继承Java标准的Iterable）
// 具体集合类（书架）
class BookShelf implements Iterable<Book> {
    private Book[] books;
    @Getter
    private int size;
    private int capacity;

    public BookShelf(int capacity) {
        this.capacity = capacity;
        this.books = new Book[capacity];
    }

    public void addBook(Book book) {
        if (size >= capacity) {
            throw new IllegalStateException("书架已满");
        }
        books[size++] = book;
    }

    @Override
    public Iterator<Book> iterator() {
        return new BookShelfIterator();
    }

    // 内部类实现迭代器
    private class BookShelfIterator implements Iterator<Book> {
        private int index = 0;

        @Override
        public boolean hasNext() {
            return index < size;
        }

        @Override
        public Book next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return books[index++];
        }

        @Override
        public void remove() {
            if (index <= 0) {
                throw new IllegalStateException("尚未调用next()或已删除元素");
            }
            // 移除当前元素（需调整数组）
            System.arraycopy(books, index, books, index - 1, size - index);
            size--;
            index--;
        }
    }
}


// 客户端
public class Client {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf(3);
        bookShelf.addBook(new Book("Java编程思想"));
        bookShelf.addBook(new Book("设计模式"));
        bookShelf.addBook(new Book("重构"));

        // 方式1：标准迭代器
        Iterator<Book> iterator = bookShelf.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().getName());
        }

        // 方式2：for-each语法糖（本质使用迭代器）
        for (Book book : bookShelf) {
            System.out.println(book.getName());
        }

        // 方式3：Java 8 Stream API
        bookShelf.forEach(book -> System.out.println(book.getName()));
    }
}